package ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import ssm.pojo.Book;
import ssm.pojo.PageInfo;
import ssm.pojo.Result;
import ssm.service.IBookService;
import ssm.service.ITypeService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: lzp
 * @Date: 2020/10/5 10:11
 * @Description: 书籍控制器
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    IBookService bookService;
    @Autowired
    ITypeService typeService;

    /**
     * 查找所有书籍
     *
     * @param pageInfo
     * @return
     */
    @RequestMapping("/findAll")
    @ResponseBody
    public PageInfo<Book> findAll(PageInfo<Book> pageInfo) {
        pageInfo.setKeyWord("%" + pageInfo.getKeyWord() + "%");
        bookService.findAll(pageInfo);
        return pageInfo;
    }


    /**
     * 添加书籍，并上传封面
     *
     * @param book
     * @param typeId
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(Book book, int typeId,HttpServletRequest request, MultipartFile upload) {
        Result result = new Result();
        //上传封面
        if(upload == null){
            //为空则设置默认封面
            book.setImg("0.png");
        }else{
            try {
                //上传的位置
                String path = request.getSession().getServletContext().getRealPath("/upload/face/");
                //判断，该路径是否存在
                File file = new File(path);
                if (!file.exists()) {
                    //创建该文件夹
                    file.mkdir();
                }
                //获取上传文件的名称和后缀
                String filename = upload.getOriginalFilename();
                String suffix = filename.substring(filename.indexOf('.'));
                //通过文件后缀判断文件类型
                if(!suffix.equalsIgnoreCase(".jpg") &&
                        !suffix.equalsIgnoreCase(".png") &&
                        !suffix.equalsIgnoreCase(".gif")){
                    result.setFlag(false);
                    result.setMsg("不支持该格式的封面图片上传！！");
                    return result;
                }
                //把文件的名称设置一致，uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //直接使用UUID+文件后缀命名
                filename = uuid + "_" + filename.substring(filename.indexOf('.'));
                book.setImg(filename);
                //完成文件上传
                upload.transferTo(new File(path, filename));
            } catch (Exception e) {
                e.printStackTrace();
                result.setFlag(false);
                result.setMsg("封面图片上传失败！！");
                return result;
            }
        }
        //通过分类id查找到相应的分类并设置
        book.setType(typeService.findById(typeId));
        // 返回数据
        book.setCreateTime(new Date());
        result.setFlag(bookService.add(book));
        if (result.getFlag()) {
            result.setMsg("书籍添加成功！！");
        } else {
            result.setMsg("书籍添加失败！！");
        }
        return result;
    }

    /**
     * 按书籍id查找
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    @ResponseBody
    public Book findById(int id) {
        return bookService.findById(id);
    }

    /**
     * 修改书籍
     *
     * @param book
     * @param typeId
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Result update(Book book, int typeId,HttpServletRequest request, MultipartFile upload) {
        Result result = new Result();
        //上传封面
        if(upload != null){
            try {
                //上传的位置
                String path = request.getSession().getServletContext().getRealPath("/upload/face/");
                //判断，该路径是否存在
                File file = new File(path);
                if (!file.exists()) {
                    //创建该文件夹
                    file.mkdir();
                }
                //获取上传文件的名称和后缀
                String filename = upload.getOriginalFilename();
                String suffix = filename.substring(filename.indexOf('.'));
                //通过文件后缀判断文件类型
                if(!suffix.equalsIgnoreCase(".jpg") &&
                        !suffix.equalsIgnoreCase(".png") &&
                        !suffix.equalsIgnoreCase(".gif")){
                    result.setFlag(false);
                    result.setMsg("不支持该格式的封面图片上传！！");
                    return result;
                }
                //把文件的名称设置一致，uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //直接使用UUID+文件后缀命名
                filename = uuid + "_" + filename.substring(filename.indexOf('.'));
                book.setImg(filename);
                //完成文件上传
                upload.transferTo(new File(path, filename));
            } catch (Exception e) {
                e.printStackTrace();
                result.setFlag(false);
                result.setMsg("封面图片上传失败！！");
                return result;
            }
        }
        //设置分类
        book.setType(typeService.findById(typeId));
        // 返回数据
        result.setFlag(bookService.update(book));
        if (result.getFlag()) {
            result.setMsg("书籍修改成功！！");
        } else {
            result.setMsg("书籍修改失败！！");
        }
        return result;
    }

    /**
     * 删除单个
     *
     * @param id
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public Result del(int id) {
        boolean flag = bookService.del(id);
        Result result = new Result();
        result.setFlag(flag);
        if (flag) {
            result.setMsg("图书删除成功！！");
        } else {
            result.setMsg("图书删除失败！！");
        }
        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(int[] ids) {
        boolean flag = true;
        for (int id : ids) {
            if (!bookService.del(id)) {
                flag = false;
            }
        }
        Result result = new Result();
        result.setFlag(flag);
        if (flag) {
            result.setMsg("删除成功！！");
        } else {
            result.setMsg("删除失败！！");
        }
        return result;
    }

    /**
     * 通过分类ID查找书籍
     *
     * @param pageInfo
     * @return
     */
    @RequestMapping("/findByTypeId")
    @ResponseBody
    public PageInfo<Book> findByTypeId(PageInfo<Book> pageInfo) {
        bookService.findByTypeId(pageInfo);
        return pageInfo;
    }


    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(HttpServletRequest request, MultipartFile upload,String username) {
        System.out.println(upload);
        System.out.println(username);
        Result result = new Result();
        if(upload == null){

        }else{
            try {
                //上传的位置
                String path = request.getSession().getServletContext().getRealPath("/upload/face/");
                //判断，该路径是否存在
                File file = new File(path);
                if (!file.exists()) {
                    //创建该文件夹
                    file.mkdir();
                }
                //获取上传文件的名称和后缀
                String filename = upload.getOriginalFilename();
                String suffix = filename.substring(filename.indexOf('.'));
                //通过文件后缀判断文件类型
                if(!suffix.equalsIgnoreCase(".jpg") &&
                        !suffix.equalsIgnoreCase(".png") &&
                        !suffix.equalsIgnoreCase(".gif")){
                    result.setFlag(false);
                    result.setMsg("不支持该格式的文件上传！！");
                    return result;
                }
                //把文件的名称设置一致，uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //直接使用UUID+文件后缀命名
                filename = uuid + "_" + filename.substring(filename.indexOf('.'));
                //完成文件上传
                upload.transferTo(new File(path, filename));
            } catch (Exception e) {
                e.printStackTrace();
                result.setFlag(false);
                result.setMsg("文件上传失败！！");
                return result;
            }
        }
        result.setFlag(true);
        result.setMsg("文件上传成功!!");
        return result;
    }
}
